package com.framework.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.annotation.DataLogAnnotation;
import com.framework.common.live.TencentLiveKit;
import com.framework.common.utils.QuickHelper;
import com.framework.common.utils.R;
import com.framework.common.utils.ResponseCode;
import com.framework.common.utils.SpringContextUtils;
import com.framework.modules.sys.entity.SysConfigEntity;
import com.framework.modules.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("app/config")
@Api(tags = "AppConfigController")
public class AppConfigController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysConfigService sysConfigService;

    @RequiresPermissions("app:config:operation")
    @DataLogAnnotation(value = "修改运营设置", filter = "post")
    @RequestMapping(value = "operation")
    public R map(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("运营设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:live")
    @DataLogAnnotation(value = "修改直播设置", filter = "post")
    @RequestMapping("live")
    public R live(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("直播设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                logger.info(String.format("正在更新系统配置 = %s", key));
                if ("zhibo.sdk.config".equals(key)) {
                    JSONObject obj = QuickHelper.json2object(value, JSONObject.class);
                    String active = obj.getString("active");
                    JSONObject activeConfig = obj.getJSONObject("templateConfig").getJSONObject(active);
                    String templateId = activeConfig.getString("TemplateId");

                    Map<String, String> attrs = new HashMap<>();
                    Iterator it = activeConfig.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, Object> liveEntry = (Map.Entry<String, Object>) it.next();
                        String name2 = liveEntry.getKey();
                        Object value2 = liveEntry.getValue();
                        attrs.put(name2, value2 == null ? "" : value2.toString());
                    }

                    Boolean result = TencentLiveKit.updateTencentLiveNotifyTemplate(Long.valueOf(templateId), attrs, obj.getString("secretId"), obj.getString("secretKey"));
                    logger.info(String.format("同步推流模板设置　= %s", result));
                    if (result) {
                        sysConfigService.updateValueByKey(key, value);
                    }
                } else {
                    sysConfigService.updateValueByKey(key, value);
                }
                logger.info(String.format("系统配置 = %s , 更新完成", key));
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:sms")
    @DataLogAnnotation(value = "修改短信设置", filter = "post")
    @RequestMapping("sms")
    public R sms(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("短信设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:sns")
    @DataLogAnnotation(value = "修改社交设置", filter = "post")
    @RequestMapping("sns")
    public R sns(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("社交设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:general")
    @DataLogAnnotation(value = "常规设置", filter = "post")
    @RequestMapping("general")
    public R general(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {

        HttpServletRequest request = SpringContextUtils.getCurrentRequest();
        logger.info(String.format("uri = %s ,queryString = %s ,  action = %s", request.getRequestURI(),request.getQueryString(), action));
        logger.info(QuickHelper.object2json(body));

        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("常规设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Boolean result = sysConfigService.updateValueByKey(key, value);
                logger.info(String.format("更新配置 %s 结果 : %s", key, result ? "成功" : "失败"));
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:servers")
    @DataLogAnnotation(value = "服务设置", filter = "post")
    @RequestMapping("servers")
    public R servers(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("服务设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:juhe")
    @DataLogAnnotation(value = "聚合数据SDK", filter = "post")
    @RequestMapping("juhe")
    public R juhe(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("聚合数据SDK");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }

    @RequiresPermissions("app:config:payment")
    @DataLogAnnotation(value = "支付设置", filter = "post")
    @RequestMapping("payment")
    public R payment(@RequestParam(value = "action", defaultValue = "get") String action, @RequestBody(required = false) Map<String, String> body) {
        if ("get".equalsIgnoreCase(action)) {
            List<SysConfigEntity> list = sysConfigService.queryByCategoryName("支付设置");
            Map<String, SysConfigEntity> maps = new LinkedHashMap<>();
            for (SysConfigEntity entity : list) {
                maps.put(entity.getParamKey(), entity);
            }
            return R.ok(maps);
        }

        if ("post".equalsIgnoreCase(action)) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sysConfigService.updateValueByKey(key, value);
            }
            return R.ok(body);
        }

        return R.response(ResponseCode.NONE);
    }
}
